﻿using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Web;
using Enyim.Caching;
using Ayatta.Contract;
using System.Web.Mvc;
using Ayatta.Contract.Domain;
using Web.Base.Extensions;
using Web.Manage.Controllers;
using Ayatta.Contract.Extension;
using System.Collections.Generic;
using Web.Manage.Areas.Game.Models;

namespace Web.Manage.Areas.Game.Controllers
{
    public class NoviceCardController : AdminBaseController
    {

        public NoviceCardController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient)
            : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        public ActionResult Index(int page = 1, int size = 50, int serverId = 0, int? userId = null, byte? status = null, DateTime? date = null)
        {
            var model = new NoviceCardControllerModel.Index();
            var games = GetGames();
            var servers = games.GetAllServers();
            var gameId = 0;
            if (serverId > 0)
            {
                var server = servers.FirstOrDefault(o => o.Id == serverId);
                if (server != null)
                {
                    gameId = server.GameId;
                }
            }
            if (userId > 0|| date.HasValue)
            {
                status = 1;
            }
            model.ServerId = serverId;
            model.UserId = userId;
            model.Status = status;
            model.Date = date;
            model.Games = games;
            model.Servers = servers;
            model.Cards = GameService.GetPagedGameNoviceCard(page, size, gameId, serverId, userId, status, date).ToPagedList(page, size);
            return PartialView(model);
        }

        public ActionResult Upload()
        {
            var model = GetGames();
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult Upload(int? gameId, HttpPostedFileBase filedata)
        {
            if (!gameId.HasValue || gameId.Value < 0)
            {
                return Json(new { status = true, msg = "请选择游戏！" });
            }
            if (filedata != null)
            {
                List<string> list;
                if (Path.GetExtension(filedata.FileName.ToLower()) == ".csv")
                {
                    string csv;
                    using (var streamReader = new StreamReader(filedata.InputStream))
                    {
                        csv = streamReader.ReadToEnd();
                    }
                    //var books =csv.Split('\n').Select(line => new {line, parts = line.Split(',')}).Select(t => new {Isbn = t.parts[0], Title = t.parts[1], Publisher = t.parts[3]});
                    list = csv.Split('\n').Select(o => o.Trim()).Where(o => !string.IsNullOrEmpty(o)).ToList();
                }
                else
                {
                    var temp = new List<string>();
                    using (var streamReader = new StreamReader(filedata.InputStream))
                    {
                        string sLine;
                        while ((sLine = streamReader.ReadLine()) != null)
                        {
                            temp.Add(sLine.Trim());
                        }
                    }
                    list = temp;
                }

                var result = GameService.UploadGameNoviceCard(gameId.Value, list.ToArray());
                if (result)
                {
                    var count = GameService.CheckGameNoviceCard(gameId.Value);
                    if (count >= 0)
                    {
                        return Json(new { status = true, msg = "成功上传并导入数据库（" + list.Count() + ")条！" });
                    }
                    return Json(new { status = false, msg = "成功上传并导入，但去重失败！" });
                }
                return Json(new { status = false, msg = "请选择正确的文件！" });
            }
            return Json(new { status = false, msg = "请选择正确的文件！" });
        }
    }
}
